package com.newgrand.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.newgrand.mapper.FgSimpleDataMapper;
import com.newgrand.model.Fg3User;
import com.newgrand.mapper.Fg3UserMapper;
import com.newgrand.mapper.UIPCommonMapper;
import com.newgrand.model.FgSimpleData;
import com.newgrand.service.impl.UipLog;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhanglixin
 * @Data: 2022/11/17 9:14
 * @Description: TODO
 */
@Slf4j
@Api(tags = "i8单点登录接口")
@RestController
@RequestMapping("/SSO")
public class SSOController {

    @Value("${i8.url}")
    private String i8Url;

    @Value("${i8.databaseName}")
    private String databaseName;

    @Value("${i8.database}")
    private String database;

    @Value("${oa.url}")
    private String oaUrl;
    @Autowired
    private Fg3UserMapper fg3UserMapper;

    @Autowired
    private UIPCommonMapper uipCommonMapper;
    @Autowired
    private UipLog uipLog;

    @Autowired
    private FgSimpleDataMapper fgSimpleDataMapper;

    @RequestMapping("/wfmsg")
    public void Wfmsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String logid = request.getParameter("logid");
        String database = request.getParameter("database");
        String orgid = request.getParameter("orgid");
        String openUrl = request.getParameter("openUrl");
        String urlTitle = request.getParameter("urlTitle");
        String openAlone = request.getParameter("openAlone");
        openUrl = URLEncoder.encode(openUrl, "UTF-8");

        QueryWrapper<Fg3User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userno",logid);
        Fg3User fg3User = fg3UserMapper.selectOne(queryWrapper);

        if (fg3User == null) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("用户不存在");
        } else {
            String userPwdStr = fg3User.getPwd();
            if (userPwdStr == null) {
                userPwdStr = "";
            } else {
                userPwdStr = java.net.URLEncoder.encode(userPwdStr, "utf-8");
            }
            String url = i8Url + "/Sup/NG3WebLogin/SignLogin?logid=" + logid + "&pwd=" + userPwdStr + "&database=" + database + "&orgid="+orgid+"&openUrl="+openUrl+"&urlTitle="+urlTitle+"&openAlone="+openAlone;
            //dbLog.info("wfmsg", "单点返回url：" + url);
            response.sendRedirect(url);
        }
    }

    @RequestMapping("/login")
    public void Login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ticket = request.getParameter("ticket");
        //uipLog.info("login", "获取到的ticket:",ticket);
        if(StringUtils.isEmpty(ticket)){
            response.sendRedirect(oaUrl);
            return;
        }
        String logid="";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建 Get 请求
        HttpGet httpGet = new HttpGet(oaUrl+"/seeyon/thirdpartyController.do?ticket="+ticket);
        //响应
        CloseableHttpResponse resp = null;
        try {
            //添加请求配置，设置响应时间等
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000) //服务器响应超时时间
                    .setConnectionRequestTimeout(2000) //连接服务器超时时间
                    .build();

            //将配置信息添加到 httpGet 中
            httpGet.setConfig(requestConfig);

            //连接，获取网页
            resp = httpClient.execute(httpGet);
            logid = resp.getFirstHeader("LoginName").getValue();
            //uipLog.info("login", "获取到的logid1:",logid);

            Header[] allHeaders = resp.getAllHeaders();
            for (int i = 0; i < allHeaders.length; i++) {
                String name = allHeaders[i].getName();
                String value = allHeaders[i].getValue();
                //uipLog.info("login", "获取到的请求头信息:",name + ":" + value);
                if("LoginName".equals(name)){
                    logid = value;
                    //uipLog.info("login", "获取到的请求头信息:","找到请求头");
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //资源释放
            if (httpGet != null) {
                try {
                    httpGet.clone();
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        QueryWrapper<Fg3User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userno",logid);
        Fg3User fg3User = fg3UserMapper.selectOne(queryWrapper);

        if (fg3User == null) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("用户不存在");
        } else {
            if("1".equals(fg3User.getMucpwd())){
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("phid", fg3User.getPhid());
                updateWrapper.set("mucpwd",  0);
                fg3UserMapper.update(null,updateWrapper);
            }
            String userPwdStr = fg3User.getPwd();
            if (userPwdStr == null) {
                userPwdStr = "";
            } else {
                userPwdStr = java.net.URLEncoder.encode(userPwdStr, "utf-8");
            }
            String url = i8Url + "/Sup/NG3WebLogin/SignLogin?logid=" + logid + "&pwd=" + userPwdStr + "&database=" + databaseName + "&orgid=&openUrl=&urlTitle=&openAlone="+false;
            //
            //url = "ngChrome://cmd&url="+url;//用i8专用浏览器打开
            //uipLog.info("login", "单点返回url:",url);
            response.sendRedirect(url);
        }
    }

    @RequestMapping("/loginApp")
    public void LoginApp(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String logid="0000";

        String ticket = request.getParameter("ticket");
        uipLog.info("loginApp", "获取到的ticket:",ticket);
        if(StringUtils.isEmpty(ticket)){
            response.sendRedirect(oaUrl);
            return;
        }

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建 Get 请求
        HttpGet httpGet = new HttpGet(oaUrl+"/seeyon/thirdpartyController.do?ticket="+ticket);
        //响应
        CloseableHttpResponse resp = null;
        try {
            //添加请求配置，设置响应时间等
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000) //服务器响应超时时间
                    .setConnectionRequestTimeout(2000) //连接服务器超时时间
                    .build();

            //将配置信息添加到 httpGet 中
            httpGet.setConfig(requestConfig);

            //连接，获取网页
            resp = httpClient.execute(httpGet);
            logid = resp.getFirstHeader("LoginName").getValue();
            //uipLog.info("login", "获取到的logid1:",logid);

            Header[] allHeaders = resp.getAllHeaders();
            for (int i = 0; i < allHeaders.length; i++) {
                String name = allHeaders[i].getName();
                String value = allHeaders[i].getValue();
                //uipLog.info("login", "获取到的请求头信息:",name + ":" + value);
                if("LoginName".equals(name)){
                    logid = value;
                    //uipLog.info("login", "获取到的请求头信息:","找到请求头");
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //资源释放
            if (httpGet != null) {
                try {
                    httpGet.clone();
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        QueryWrapper<Fg3User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userno",logid);
        Fg3User fg3User = fg3UserMapper.selectOne(queryWrapper);

        if (fg3User == null) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("用户不存在");
        } else {
            if("1".equals(fg3User.getMucpwd())){
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("phid", fg3User.getPhid());
                updateWrapper.set("mucpwd",  0);
                fg3UserMapper.update(null,updateWrapper);
            }
            String userPwdStr = fg3User.getPwd();
            if (userPwdStr == null) {
                userPwdStr = "";
            } else {
                userPwdStr = java.net.URLEncoder.encode(userPwdStr, "utf-8");
            }

            String url = i8Url + "/Hnlj/static/index.html?userno="+fg3User.getUserno()+"_"+database;
            //            //url = "ngChrome://cmd&url="+url;//用i8专用浏览器打开
            //uipLog.info("login", "单点返回url:",url);
            response.sendRedirect(url);
        }
    }

    @RequestMapping(value = "/GetH5Link",method = RequestMethod.GET)
    @ResponseBody
    public Object GetH5Link()
    {
        Map<String,Object> rtnJson = new HashMap<>();
        QueryWrapper<FgSimpleData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_type","H5Config");
        List<FgSimpleData> fgSimpleDataList = fgSimpleDataMapper.selectList(queryWrapper);
        if(fgSimpleDataList==null||fgSimpleDataList.size()==0){
            rtnJson.put("code","9999");
            rtnJson.put("msg","查询不到数据");
            return rtnJson;
        }
        rtnJson.put("code","0");
        rtnJson.put("msg","");
        rtnJson.put("data",fgSimpleDataList);
        return rtnJson;
    }

}
